package com.gin.kotlin.gf2gamecommunity.base.composable

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

/**
 * 指示器配置
 * @param selectedColor 已选中指示器颜色
 * @param unselectedColor 未选中指示器颜色
 * @param size 指示器大小
 * @param spacing 指示器间隔
 * @param range 指示器距离容器底边的距离
 * @param shape 指示器形状
 * @constructor
 */
data class IndicatorConfig(
    val selectedColor: Color = Color.Blue,
    val unselectedColor: Color = Color.Gray,
    val size: Dp = 10.dp,
    val spacing: Dp = 8.dp,
    val range: Dp = 8.dp,
    val shape: Shape = CircleShape,
)

/**
 * 带指示器的横向分页器
 * @param T 数据类型
 * @param data 数据列表
 * @param pagerState [PagerState]
 * @param pageSpacing 页间距
 * @param backgroundColor 背景颜色
 * @param indicatorConfig 指示器配置
 * @param modifier Modifier
 * @param item (T) -> Unit
 */
@Composable
fun <T> HorizontalPagerWithIndicator(
    data: List<T>,
    pagerState: PagerState,
    pageSpacing: Dp = 8.dp,
    indicatorConfig: IndicatorConfig = IndicatorConfig(),
    backgroundColor: Color = Color.DarkGray,
    modifier: Modifier = Modifier,
    item: @Composable (T) -> Unit
) {
    Box(Modifier.background(backgroundColor)) {
        HorizontalPager(state = pagerState, modifier = modifier, pageSpacing = pageSpacing) { page -> item(data[page]) }

        if (pagerState.pageCount > 1) {
            // 页数指示器
            indicatorConfig.apply {
                Row(Modifier
                    .align(Alignment.BottomCenter)
                    .padding(range)) {
                    repeat(data.size) {
                        Box(Modifier
                            .clip(shape)
                            .background(if (it == pagerState.currentPage) selectedColor else unselectedColor)
                            .width(size)
                            .height(size))
                        Spacer(Modifier.width(spacing))
                    }
                }
            }
        }
    }
}